package com.ssy.lingxi.system.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.system.config.exception.LoginException;
import com.ssy.lingxi.system.dto.response.MiddlegroundUserLoginResponse;
import com.ssy.lingxi.system.service.ITokenAndAuthService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 客户端请求Token和权限验证接口实现
 * @author 王日灿
 * @version 2.0.0
 * @date 2020-06-07
 */
@Service
public class TokenAndAuthServiceImpl implements ITokenAndAuthService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 前端请求包含在Http Headers中的Token的Key
     */
    private static final  String TOKEN_AUTHORIZATION_KEY = "token";

    /**
     * 前端请求包含在Http Headers中的会员Id的Key
     */
    private static final String MEMBER_AUTHORIZATION_KEY = "mid";

    /**
     * 指定不需要进行Token和Auth验证的Url
     */
    private static final List<String> excludeUrlList =
            Stream.of("/middleground/user/login", "/menu/tree", "/system/menu/tree","/system/menu/code/list","/menu/code/list").collect(Collectors.toList());

    @Override
    public boolean authToken(String token,String requestPath) {
        //过滤不需要验证的Url
        if (excludeUrlList.contains(requestPath)) {
            return true;
        }
        //验证token是否存在
        if (null == token) {
            throw new LoginException(ResponseCode.TOKEN_INEXISTENCE.getMessage(), ResponseCode.TOKEN_INEXISTENCE.getCode());
        }
        //根据token获取用户信息
        String userJson = stringRedisTemplate.opsForValue().get(token);
        if (userJson == null||userJson.isEmpty()) {
            throw new LoginException(ResponseCode.TOKEN_DOES_NOT_EXIST_IN_CACHE.getMessage(), ResponseCode.TOKEN_DOES_NOT_EXIST_IN_CACHE.getCode());
        }
        //刷新用户过期时间
        stringRedisTemplate.opsForValue().set(token,userJson,7200, TimeUnit.SECONDS);
        //改成使用fasterxml.jackson
        ObjectMapper mapper = new ObjectMapper();
        MiddlegroundUserLoginResponse middlegroundUserLoginResponse = null;
        try {
            middlegroundUserLoginResponse = mapper.readValue(userJson,MiddlegroundUserLoginResponse.class);
        } catch (Exception e) {
            throw new LoginException("用户信息解析异常", ResponseCode.TOKEN_DOES_NOT_EXIST_IN_CACHE.getCode());
        }
        //TODO 去掉权限校验 正式环境部署后放开注释
//        List<RoleLoginResponse> roles = middlegroundUserLoginResponse.getRoles();
//        Set<String> menuPaths= new HashSet();
//        roles.forEach(role->{
//            List<MenuLoginResponse> menus = role.getMenus();
//            Set<String> collect = menus.stream().map(menu -> menu.getPath()).collect(Collectors.toSet());
//            menuPaths.addAll(collect);
//        });
//        if(!menuPaths.contains(requestPath)){
//            throw  new LoginException(ResponseCode.INSUFFICIENT_PRIVILEGES.getNameByCode(), ResponseCode.INSUFFICIENT_PRIVILEGES.getCode());
//        }

        return true;
    }
}
